<?php

class MediaController extends Controller {
    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction = 'index';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',  // allow all users to perform 'list' and 'show' actions
                'actions' => array(
                    'list', 'listicon', 'show', 'uploading', 'selectMediaFile',
                    'autoComplete', 'ajaxDelete', 'downloading', 'showCategoryMediaList',
                    'search', 'changeCategory', 'showUploadingZone', 'index'
                ),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin','delete'),
                'users' => array('admin'),
            ),
            array('deny',  // deny all users
                'users' => array('*'),
            ),
        );
    }

    // 改变 media 分类
    public function actionChangeCategory() {
//        $source = Yii::app()->request->getPost('source');
        $target = Yii::app()->request->getPost('target');
        $ids = Yii::app()->request->getPost('ids');
        $ids_fix = explode(',', $ids);
        $category_name = MediaCategory::model()->findByPk($target)->name;
        if (intval($target) > 0) {
            foreach ($ids_fix as $id) {
                $model = Media::model()->find(array(
                    'condition' => "id = {$id}",
                    'select' => array('id', 'category_id'),
                ));
                $source = $model->category_id;
                if (intval($target) != intval($source)) {
//                if (Media::model()->updateByPk($id, array('category_id' => $target))) {
                    $model->category_id = $target;
                    if ($model->save(false)) {
                        MediaCategory::model()->updateCounters(array('files_count' => -1), "id = {$source}");
                        MediaCategory::model()->updateCounters(array('files_count' => 1), "id = {$target}");
                    }
                }
            }
            echo $category_name;
        } else {
            echo '0';
        }
    }

    // 搜索
    public function actionSearch() {
        $q = Yii::app()->request->getParam('q');

        // 将查询值放于 Cookie 中
        $cookie= new CHttpCookie('sw_file_name', $q);
        Yii::app()->request->cookies['sw_file_name'] = $cookie;

        $criteria = new CDbCriteria();
        $criteria->condition = "file_name LIKE '%{$q}%'";
        $criteria->order = 'file_name ASC';
        
        $pages = new CPagination(Media::model()->count($criteria));
        $pages->pageSize = 10;
        $pages->applyLimit($criteria);

        $models = Media::model()->findAll($criteria);

        if (Yii::app()->request->isAjaxRequest) {
            $this->renderPartial("showCategoryMediaListIcon", array(
                'models' => $models,
                'pages' => $pages,
                'element_id' => $element_id,
                ), false, true);
        } else {
            $this->render("showCategoryMediaListIcon", array(
                'models' => $models,
                'pages' => $pages,
                'element_id' => $element_id,
                ));
        }
    }


    public function actionShowCategoryMediaList() {
//        $showType = Yii::app()->request->getParam('show_type', 'text');
        $showType = 'text';
//        echo Yii::app()->request->requestType;
//        exit;
        switch ($showType) {
            case 'icon':
                $show_type = "Icon";
                break;
            case 'text':
                $show_type = 'Text';
                break;
            case 'table':
                $show_type = 'Table';
                break;
            default:
                $show_type = 'Text';
        }
//        echo $show_type;
//        exit;
        $element_id = Yii::app()->request->getParam('element_id');
        $category_id = Yii::app()->request->getParam('category_id');
        $criteria = new CDbCriteria();
        $criteria->condition = "category_id = {$category_id}";
        $criteria->order = 'file_name ASC';

        $pages = new CPagination(Media::model()->count($criteria));
        $pages->pageSize = 120;
        $pages->applyLimit($criteria);

        $sort = new CSort('Media');
        $sort->applyOrder($criteria);

        $models = Media::model()->findAll($criteria);

        if (Yii::app()->request->isAjaxRequest) {
            $this->renderPartial("showCategoryMediaList{$show_type}", array(
                'models' => $models,
                'pages' => $pages,
                'category_id' => $category_id,
                'element_id' => $element_id,
                'sort' => $sort
                ) ,false, true);
        } else {
            $this->render("showCategoryMediaList{$show_type}", array(
                'models' => $models,
                'pages' => $pages,
                'category_id' => $category_id,
                'element_id' => $element_id,
                'sort' => $sort
                ));
        }
    }

    // 自动完成功能
    public function actionAutoComplete() {
//        echo Yii::app()->request->getParam('q');
        $criteria = new CDbCriteria();
        $criteria->condition = "file_name LIKE :file_name";
        $criteria->params = array(":file_name" => "%" . Yii::app()->request->getParam('q') . "%");
        $criteria->select = array('file_name', 'file_extension');
        $items = Media::model()->findAll($criteria);
        $results = array();
//        $img = CHtml::image(Yii::app()->baseUrl . '/assets/backend/images/mime/icon_7z_small.png',
//            'aaa', array('style' => 'padding: 0; margin: 0, padding-top: 12px;'));
        foreach ($items as $item) {
            $results[] = "{$item->file_name}";
        }
        echo join("\n", $results);
    }

    // Media 文件选择框
    public function actionSelectMediaFile() {
        $this->layout = 'contents';
        if (Yii::app()->request->isAjaxRequest) {
            // only allow ajax request
            // 同时只显示指定类型的数据
            $type = Yii::app()->request->getParam('type');
            $element_id = Yii::app()->request->getParam('element_id');
            $configs = Yii::app()->params["media_types"]["{$type}"];
            $types = array();
            foreach ($configs as $config) {
                $types[] = substr($config, 2, strlen($config));
            }

            $criteria = new CDbCriteria();
            $criteria->addInCondition('file_extension', $types);
            $criteria->order = 'file_name ASC';

            $pages->pageSize = $config['per_page_size'];

            $models = Media::model()->findAll($criteria);

            $this->render('selectMediaFile', array(
                'models' => $models,
                'pages' => $pages,
                'element_id' => $element_id,
            ));
        }
    }

    // 下载文件
    public function actionDownloading() {
        $media = $this->loadMedia();
        if ($media->id) {
            $file = Yii::app()->file->set($media->mediaSavedPath, true);
            $file->download();
        }
    }

    // ajax upload files
    public function actionUploading() {
        ini_set("memory_limit", "-1");
        set_time_limit(0);
        $uploading_file = CUploadedFile::getInstanceByName('Filedata');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
            $media_category_id = Yii::app()->request->getParam('media_category_id', 1);
            $extension_name = strtolower($uploading_file->getExtensionName());
            $file_name = $uploading_file->getName();
            $file_name = substr($file_name, 0, strlen($file_name) - strlen($extension_name) - 1);
            $file_name_md5 = md5(time() . $file_name);
            $file_saved_path = $file_name_md5 . '.' . $extension_name;
//            echo $filename;
            $media = new Media();
            $media->category_id = $media_category_id;
            $media->file_saved_path = $file_saved_path;
            $media->file_name = $file_name;
            Yii::import('application.extensions.Hanzi.HanziTools');
            $pzt = new HanziTools();
            $media->file_name_pinyin = $pzt->getFullPinYin($file_name);
            $media->file_extension = $extension_name;
            $media->file_size = $uploading_file->getSize();
            $uploading_file->saveAs(Yii::getPathOfAlias('webroot')
                    . Yii::app()->params['upload_directory']['media'] . $file_saved_path);
            if ($uploading_file->getHasError()) {
                echo $uploading_file->getError();
            } else {
                // 如果上传的是图片文件，则根据用户的相应设置对图片进行裁剪以及添加水印
                $configs = Yii::app()->params;
                if (in_array("*.{$extension_name}", $configs->media_types['picture'])) {
                    Yii::import('application.extensions.helper.CAppHelper');
                    $app_helper = new CAppHelper();
                    $picture_thumb_saved_path = $app_helper->generatePictureThumb(
                        Yii::getPathOfAlias('webroot') . Yii::app()->params['upload_directory']['media'],
                        $file_saved_path);
//                    echo $picture_thumb_saved_path;
                    $media->picture_thumb_saved_path = $picture_thumb_saved_path;
                }
                // 图片处理结束
                if ($media->save(false)) {
                    // 更新所属分类数量
                    MediaCategory::model()->updateCounters(
                        array('files_count' => 1), "id = {$media_category_id}");
//                    if ($picture_thumb_saved_path == '') {
//                        echo 'generate picture thumb error.';
//                    }
                    echo 1;
                } else {
                    $path = Yii::getPathOfAlias('webroot') . Yii::app()->params['upload_directory']['media'];
                    @unlink($path . $file_saved_path);
                    @unlink($path . $picture_thumb_saved_path);
                    echo 'save error.' . $media->getErrors();
                }
            }
        } else {
            echo 'error';
        }
    }

    // 生成图片缩略图
    private function generatePictureThumb($source_file_saved_path) {
        
    }

    /**
     * Shows a particular model.
     */
    public function actionShow() {
        $this->layout = 'contents';
        $this->render('show', array('model' => $this->loadMedia()));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
    public function actionCreate() {
        $this->layout = 'contents';
//        CVarDumper::dump(Yii::app()->params, 10, true);
        $media_category_id = Yii::app()->request->getParam('media_category_id', 1);
        $media_category_id = (MediaCategory::model()->exists("id = {$media_category_id}"))
            ? $media_category_id
            : 1;
//        echo $media_category_id;
////        exit;
        $model = new Media;
        if (isset($_POST['Media'])) {
            $model->attributes = $_POST['Media'];
            if ($model->save()) {
                $this->redirect(array('list'));
            }
        }
        $this->render('create', array(
            'model' => $model,
            'media_category_id' => $media_category_id
        ));
    }

    // 显示上传区域，供用户上传文件
    public function actionShowUploadingZone() {
        // 只处理 aJax 提交过来的请求
        if (Yii::app()->request->isAjaxRequest) {
//            echo Yii::app()->request->getParam('category_id');
            $this->renderPartial('showUploadingZone', array(
                'media_category_id' =>Yii::app()->request->getParam('category_id')
                ), false, true);
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'list' page.
     */
    public function actionUpdate() {
        $this->layout = 'contents';
        $model = $this->loadMedia();
        if (isset($_POST['Media'])) {
            $model->attributes = $_POST['Media'];
            if ($model->save()) {
                $this->redirect(array('list', 'id' => $model->category_id));
            }
        }
        $this->render('update', array('model' => $model));
    }

    // Ajax 方式删除单个文件
    public function actionAjaxDelete() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getParam('id');
            $media = Media::model()->findByPk($id);
            if ($media->id) {
                echo ($media->delete()) ? '1' : 0;
            } else {
                echo '点得太快啦！(*^__^*)';
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            $delete = Yii::app()->request->getPost('delete');
            foreach ($delete as $id) {
                Media::model()->findByPk($id)->delete();
            }
            
            $this->redirect(array('list'));
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    // 图标形式显示数据
    public function actionListIcon() {
//        $media_types = Yii::app()->params['media_types'];
//        CVarDumper::dump($media_types, 100, true);
        $current_media_category = Yii::app()->request->getParam('media_category_id', 0);
        $criteria = new CDbCriteria;
        if (intval($current_media_category) != 0) {
            $criteria->condition = "category_id = {$current_media_category}";
        }
        $pages = new CPagination(Media::model()->count($criteria));
        $config = Yii::app()->params['backend'];
        $pages->pageSize = $config['per_page_size'];
        $pages->applyLimit($criteria);
        $models = Media::model()->findAll($criteria);

        $this->render('listicon', array(
            'models' => $models,
            'pages' => $pages,
//            'current_media_category' => $current_media_category,
        ));
    }

    // 主界面
    public function actionIndex() {
        $this->renderPartial('index', null, false, true);
    }

    /**
     * Lists all models.
     */
    public function actionList() {
        $this->layout = 'contents';
        $this->processAdminCommand();

        $category = Yii::app()->request->getParam('id', 0);
        $criteria = new CDbCriteria;
        $criteria->condition = "category_id = {$category}";

        $pages = new CPagination(Media::model()->count($criteria));
        $config = Yii::app()->params['backend'];

        $pages->pageSize = $config['per_page_size'];
        $pages->applyLimit($criteria);

        $sort = new CSort('Media');
        $sort->applyOrder($criteria);

        $models = Media::model()->findAll($criteria);

        $this->render('list', array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadMedia($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=Media::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadMedia($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
